import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/finished_out_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_move_line_odoo_api.dart';
import 'package:flutter_admin/api/odoo/stock_quant_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_out.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/delivery.dart';
import 'package:flutter_admin/pages/odoo/material/finished_out/ship_the_products.dart';
import 'package:flutter_admin/pages/odoo/material/location_in/stock_quant_print_dialog.dart';
import 'package:flutter_admin/pages/odoo/material/location_out/location_out_confirmation.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/bluetooth.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class StockQuantPintList extends StatefulWidget {
  StockQuantPintList({Key? key}) : super(key: key);

  @override
  _StockQuantPintListState createState() => _StockQuantPintListState();
}

class _StockQuantPintListState extends State<StockQuantPintList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
  PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  List<StockQuant> selectedList = [];
  //车间
  List<SelectOptionVO> workshopList = [];
  //库房
  List<SelectOptionVO> locationList = [];

  StockQuant stockQuant = StockQuant();

  UserInfo userInfo = StoreUtil.getCurrentUserInfo();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    ResponseBodyApi res = await StockMoveLineOdooApi.getLocation(userInfo.userId);
    if (res.success!){
      for(var i = 0; i < res.data.length; i++){
        locationList.add(SelectOptionVO(value: res.data[i]["locaiton_id"].toString(),label: res.data[i]["locaiton_name"]));
      }
      if(res.data.length == 1){
        stockQuant.locationId = res.data[0]["location_id"].toString();
        _query();
      }
    }
    setState(() {});
  }

  String getLocationName(String locationId){
    for (var i = 0; i< locationList.length ; i++){
      if(locationList[i].value == locationId){
        return locationList[i].label!;
      }
    }
    return "";
  }

  @override
  Widget build(BuildContext context) {
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
        _operationList(),
      ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        // DataColumn(label: Text('生产单号')),
        DataColumn(label: Text('库房位置')),
        DataColumn(label: Text('库位信息')),
        DataColumn(label: Text('物料编码')),
        DataColumn(label: Text('物料名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('批次号')),
        DataColumn(label: Text('库存数量')),
        DataColumn(label: Text('单位')),
      ],
      getCells: (m) {
        StockQuant stockQuant = StockQuant.fromLocationOutMap(m);
        return [
          // DataCell(Text(stockQuant.productorderno ?? '--')),
          DataCell(Text(stockQuant.locationName ?? '--')),
          DataCell(Text(stockQuant.shelvesName ?? '--')),
          DataCell(Text(stockQuant.productCode ?? '--')),
          DataCell(Text(stockQuant.productName ?? '--')),
          DataCell(Text(stockQuant.productDes ?? '--')),
          DataCell(Text(stockQuant.batchno ?? '--')),
          DataCell(Text(stockQuant.quantity.toString())),
          DataCell(Text(stockQuant.productUomName ?? '--')),
        ];
      },
    );
    _getSelectList();
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        title: Text('标签打印'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if (isBlank(stockQuant.locationId)) {
      tableKey.currentState?.pageTo(0);
      tableKey.currentState?.loadData(PageModel());
      CryUtils.message("请选择库房位置");
      return;
    }
    ResponseBodyApi responseBodyApi = await StockQuantOdooApi.moveOutcomingSearchPage(
        data: {"page": page, "domainList": stockQuant.toMoveOutcomingSearchDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockQuantPintDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockQuant = v;
        _query();
      }
    });
  }

  _print(StockQuant stockQuant){
    String locationCode = isBlank(stockQuant.shelvesCode)?stockQuant.locationCode!:stockQuant.shelvesCode!;
    var configList = [
      {
        "label": "物料编码",
        "key": "productCode"
      },{
        "label": "物料名称",
        "key": "productName"
      },{
        "label": "规格型号",
        "key": "productDes"
      },{
        "label": "库房位置",
        "key": "locationName"
      },{
        "label": "库存数量",
        "key": "quantity"
      },{
        "label": "单位",
        "key": "productUomName"
      },
    ];
    var qrCode = stockQuant.productorderno! + "|" + stockQuant.productCode! + "|" + locationCode;
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: BluetoothView(title: '中天宽带${stockQuant.locationName}',data: stockQuant.toMap(), configList: configList,qrCode: qrCode,),
      ),
    ).then((v) {});
  }

  _getSelectList() {
    selectedList = tableKey.currentState
        ?.getSelectedList(page)
        .map<StockQuant>((e) => StockQuant.fromLocationOutMap(e))
        .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.print) {
          _print(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.print,
          enabled: selectedList.length == 1,
          child: ListTile(
            enabled: selectedList.length == 1,
            leading: const Icon(Icons.print),
            title: Text('标签打印'),
          ),
        ),
      ],
    );
  }
}
